package reso;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Enumeration;
import java.util.List;

import porte.Client;

import serveur_reso.Reso;
import serveur_reso.ResoImpl;

public class Launcher {

	public static String getAddress() {
		try {
			Enumeration<NetworkInterface> ifaceList = NetworkInterface.getNetworkInterfaces();

			while (ifaceList.hasMoreElements()) { 
				List<InterfaceAddress> ifaceAddrList = ifaceList.nextElement().getInterfaceAddresses(); 

				for (InterfaceAddress ifaceAddr : ifaceAddrList) {
					InetAddress addr = ifaceAddr.getAddress();

					if (addr.isSiteLocalAddress()){
						String hostAddr = addr.getHostAddress();
						System.out.println("Host address found: " + hostAddr);
						return hostAddr;
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} 

		System.out.println("Host address NOT found!");
		return "localhost";
	}

	public static void setServerHostname() {
		System.setProperty("java.rmi.server.hostname", getAddress()); 		
	}

	public static void main(String[] args) {

		try {
			Registry registry = LocateRegistry.createRegistry(1099);

			setServerHostname();
			
			Reso reso = new ResoImpl();
			registry.rebind(Reso.NAME, reso);

			System.out.println("Reso successfully launched!");
			
			ImplementServeurDeVoiture serveurDeVoiture = null;
			
			serveurDeVoiture = new ImplementServeurDeVoiture(Client.nombreDePortes, Client.nombreDePlaceLibre);

			
			registry.rebind(ServeurDeVoiture.NAME, serveurDeVoiture);
			
			System.out.println("ServeurDeVoiture successfully launched!");
			
			synchronized (serveurDeVoiture) {
				
				try {
					serveurDeVoiture.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			System.out.println("Start to simulEntreSortie");
			
			serveurDeVoiture.simulEntreeSortie();

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}
